package main

import (
	"fmt"
	"net"
)

type User struct {
	Name string
	Addr string
	C chan string
	conn net.Conn
}

// NewUser 创建用户API
func NewUser(conn net.Conn) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name: userAddr,
		Addr: userAddr,
		C:    make(chan string),
		conn: conn,
	}
	// 启动监听当前user  channel消息的goroutine
	go user.ListenMessage()
	return user
}

// ListenMessage 监听当前User channel的方法, 一旦有消息就直接发送给客户端
func (_this *User) ListenMessage()  {
	for {
		msg := <- _this.C
		_, err := _this.conn.Write([]byte(msg + "\n"))
		if err != nil {
			fmt.Println("Send message err: ", err)
			return
		}
	}
}
